<template>
  <ele-page flex-table :multi-card="false" hide-footer>
    <menu-search @search="reload" :cache-key="getCurrentInstance().type.name" />
    <ele-card
      :body-style="{ paddingTop: '8px' }"
      flex-table
      :multi-card="false"
      hide-footer
    >
      <ele-pro-table
        sticky
        ref="tableRef"
        row-key="menu_id"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        :highlight-current-row="true"
        :export-config="{ fileName: '菜单数据' }"
        :default-expand-all="false"
        :pagination="false"
        :cache-key="getCurrentInstance().type.name"
      >
        <template #toolbar>
          <el-button
            type="primary"
            class="ele-btn-icon"
            :icon="PlusOutlined"
            @click="openAdd()"
          >
            新建
          </el-button>
          <el-button
            class="ele-btn-icon"
            :icon="ColumnHeightOutlined"
            @click="expandAll"
          >
            展开全部
          </el-button>
          <el-button
            class="ele-btn-icon"
            :icon="VerticalAlignMiddleOutlined"
            @click="foldAll"
          >
            折叠全部
          </el-button>
        </template>
        <template #title="{ row }">
          <el-icon
            v-if="row.icon"
            :size="15"
            style="margin-right: 8px; vertical-align: -2px"
          >
            <component :is="row.icon" />
          </el-icon>
          <span>{{ row.title }}</span>
        </template>
        <template #menu_type="{ row }">
          <el-tag
            v-if="isExternalLink(row.path)"
            size="small"
            type="danger"
            :disable-transitions="true"
          >
            外链
          </el-tag>
          <el-tag
            v-else-if="isExternalLink(row.component)"
            size="small"
            type="warning"
            :disable-transitions="true"
          >
            内嵌
          </el-tag>
          <el-tag
            v-else-if="isDirectory(row)"
            size="small"
            :disable-transitions="true"
          >
            目录
          </el-tag>
          <el-tag
            v-else-if="row.menu_type === 1"
            size="small"
            type="success"
            :disable-transitions="true"
          >
            菜单
          </el-tag>
          <el-tag
            v-else-if="row.menu_type === 2"
            size="small"
            type="info"
            :disable-transitions="true"
          >
            按钮
          </el-tag>
        </template>
        <template #action="{ row }">
          <el-link type="primary" underline="never" @click="openAdd(row)">
            添加
          </el-link>
          <el-divider direction="vertical" />
          <el-link type="primary" underline="never" @click="openEdit(row)">
            修改
          </el-link>
          <el-divider direction="vertical" />
          <el-link type="primary" underline="never" @click="openView(row)">
            查看
          </el-link>
          <el-divider direction="vertical" />
          <el-link
            type="danger"
            underline="never"
            @click="action('remove', row)"
          >
            删除
          </el-link>

          <!-- 
          <el-link
            type="primary"
            underline="never"
            @click="openEdit(null, row.menu_id)"
          >
            添加
          </el-link>
          <el-divider direction="vertical" />
          <el-link type="primary" underline="never"@click="openEdit(row)">
            修改
          </el-link>
          <el-divider direction="vertical" />
          <el-link type="danger" underline="never"@click="remove(row)">
            删除
          </el-link> -->
        </template>
      </ele-pro-table>
    </ele-card>
    <!-- <menu-edit
      ref="menuEditRef"
      v-model="showEdit"
      :data="current"
      :parent-id="parent_id"
      @done="handleMenuEditDone"
    /> -->

    <!-- 新增 -->
    <menu-edit
      ref="menuEditRef"
      :parentId="parent_id"
      :parentMenuType="parentMenuType"
      action="add"
      v-model="showAdd"
      @done="handleMenuEditDone"
    />

    <!-- 修改 -->
    <menu-edit
      action="edit"
      ref="menuEditRef"
      :parentId="parent_id"
      :data="current"
      v-model="showEdit"
      @done="handleMenuEditDone"
    />

    <!-- 查看 -->
    <menu-edit
      action="view"
      ref="menuEditRef"
      :parentId="parent_id"
      :data="current"
      v-model="showView"
      @done="handleMenuEditDone"
    />
  </ele-page>
</template>

<script setup>
import { ref, getCurrentInstance } from "vue";
import { isExternalLink, toTree } from "ele-admin-plus/es";
import {
  PlusOutlined,
  ColumnHeightOutlined,
  VerticalAlignMiddleOutlined,
} from "@/components/icons";
import MenuSearch from "./components/menu-search.vue";
import MenuEdit from "./components/menu-edit.vue";
import { listMenus, removeMenuBatch } from "@/api/system/menu";
import { useTable } from "@/hooks/useTable";
import { useOperator } from "@/hooks/operator";

import { useModal } from "@/hooks/useModal";

defineOptions({ name: "SystemMenuTable" });

// 使用 useTable
const { tableRef, datasource, reload, expandAll, foldAll } = useTable({
  getPages: listMenus,
  afterQuery: (data) => {
    return toTree({
      data,
      idField: "menu_id",
      parentIdField: "parent_id",
    });
  },
});

// 使用 useOperator 处理删除操作
const { action } = useOperator({
  actionConfigs: {
    remove: {
      title: "删除",
      api: removeMenuBatch,
      confirmText: "确定要删除“{%s}”吗?",
      beforeSubmit: ({ type, rows, formData }) => {
        if (rows[0].children?.length) {
          return new Error("请先删除子节点");
        }
        return { type, rows, formData };
      },
    },
  },
  idField: "menu_id",
  idName: "title",
  reload,
});

// 表格列配置
const columns = ref([
  {
    type: "index",
    columnKey: "index",
    width: 50,
    align: "center",
    fixed: "left",
  },
  {
    prop: "title",
    label: "菜单名称",
    slot: "title",
    minWidth: 160,
  },
  {
    prop: "path",
    label: "路由地址",
    minWidth: 160,
  },
  {
    prop: "component",
    label: "组件地址",
    minWidth: 160,
  },
  {
    prop: "authority",
    label: "权限标识",
    minWidth: 160,
  },
  {
    prop: "sort_number",
    label: "排序",
    width: 100,
    align: "center",
  },
  {
    prop: "hide",
    label: "可见",
    width: 100,
    align: "center",
    formatter: (row) => ["是", "否"][row.hide],
  },
  {
    prop: "menu_type",
    label: "类型",
    width: 100,
    align: "center",
    slot: "menu_type",
    formatter: (row) =>
      ["菜单", "按钮", "外链", "内嵌", "目录"][
        isExternalLink(row.path)
          ? 2
          : isExternalLink(row.component)
            ? 3
            : isDirectory(row)
              ? 4
              : row.menu_type
      ],
  },
  {
    columnKey: "action",
    label: "操作",
    width: 180,
    align: "center",
    slot: "action",
    hideInPrint: true,
    hideInExport: true,
  },
]);

// 当前编辑数据
const current = ref(null);

// 上级菜单id
const parent_id = ref();
const parentMenuType = ref();

// 菜单编辑弹窗组件
const menuEditRef = ref(null);

// // 打开编辑弹窗
// const openEdit = (row, id) => {
//   current.value = row ?? null;
//   parent_id.value = id;
//   showEdit.value = true;
// };

// 刷新菜单下拉选择数据
const reloadMenuSelectData = () => {
  menuEditRef.value?.reloadMenuSelectData?.();
};

// 判断是否是目录
const isDirectory = (d) => {
  return !!d.children?.length && !d.component;
};

// 菜单编辑完成事件
const handleMenuEditDone = () => {
  reload();
  reloadMenuSelectData();
};

// 使用hook创建各个弹窗
const { visible: showAdd, open: openAdd } = useModal({
  beforeOpen: (row) => {
    console.log("新增前处理", row);
    parent_id.value = row?.menu_id || 0; // 确保parent_id有默认值
    parentMenuType.value = row ? row.menu_type : ""; // 确保parentMenuType有默认值
    console.log(
      "新增前处理",
      parent_id.value,
      "parentMenuType.value",
      parentMenuType.value,
    );
    current.value = null; // 重置current
  },
});

const { visible: showEdit, open: openEdit } = useModal({
  beforeOpen: async (row) => {
    // 更新useModal中的current值
    current.value = row; // 重置current
  },
});

const { visible: showView, open: openView } = useModal({
  beforeOpen: async (row) => {
    current.value = row; // 设置当前行数据
  },
});
</script>
